using Bogus;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Zhaoxi.Zhihu.Core.AppUserAggregate.Entites;
using Zhaoxi.Zhihu.Core.QuestionAggregate.Entites;
using IdentityUser = Zhaoxi.Zhihu.Infrastructure.Identity.IdentityUser;

namespace Zhaoxi.Zhihu.Infrastructure;

public class AppDbInitializer(ILogger<AppDbInitializer> logger,
    AppDbContext context,
    UserManager<IdentityUser> userManager)
{
    public async Task InitializeAsync()
    {
        try
        {
            await context.Database.MigrateAsync();

        }
        catch (Exception e)
        {
            logger.LogError(e,"初始化数据库失败");
            throw;
        }
    }

    public async Task SeedAsync()
    {
        try
        {
            await TrySeedAsync();
        }
        catch (Exception e)
        {
           logger.LogError(e,"创建种子数据出错");
            throw;
        }
    }

    private async Task TrySeedAsync()
    {
        //初始化认证用户
        var authUser = new IdentityUser { UserName = "Zilor@zhaoxi.com", Email = "zilor@zhaoxi.com" };

        if (!userManager.Users.Any(u => u.UserName != authUser.UserName))
        {
            await userManager.CreateAsync(authUser, "123456aA!");
            //创建业务用户
            var appUser = new AppUser(authUser.Id) { Nickname = "zilor", Bio = "这个家伙很懒没留下任何信息" };
            context.AppUsers.Add(appUser);
        }
        //随机生成一些文本作为虚拟数据
        if (!context.Questions.Any())
        {
            var answerFaker = new Faker<Answer>("zh_CN")
                .RuleFor(a => a.Content, f => f.Lorem.Paragraphs())
                .RuleFor(a => a.CreatedBy, authUser.Id);
            var questionFaker = new Faker<Question>("zh_CN")
                .RuleFor(q => q.Title, f => f.Lorem.Sentence(10))
                .RuleFor(q => q.Description, f => f.Lorem.Paragraphs())
                .RuleFor(q=>q.ViewCount,f=>f.Random.Number(99999))
                .RuleFor(q=>q.Answers,f=>answerFaker.GenerateBetween(1,30))
                .RuleFor(q=>q.CreatedBy,authUser.Id);
            
            var question=questionFaker.Generate(50);
            
            context.Questions.AddRange(question);
            await context.SaveChangesAsync();
                
        }
    }
}